<?php

/**
 * Description of ConnexionController
 *
 * @author FFOZEU
 */
namespace Applications\Modules\Users\Backend\Controller;

use Library\BackController;
use Library\HttpRequest;
use Library\Classe\Form\Form;

class UsersController extends BackController{
    
    public function executeConnect(HttpRequest $request){
        
        $this->page->addVar('title','login');
        if ($request->postExists('login')){
            $login = $request->postData('login');
            $password = $request->postData('password');
            
            $manager = $this->managers->getManagerOf('Users');
        
                $user = $manager->verifLogin($login, $password);
                if(empty ($user)){
                    $this->app->user()->setFlash('Le pseudo ou le mot de passe est incorrect.');
                }else{
                    $this->logIn($user);
                    if($this->app->user()->isAdmin()){
                        $this->app->httpResponse()->redirect('/admin/');
                    }else{
                        $this->app->user()->setFlash('Vous n\'avez pas les droits d\'accès');
                        $this->app->httpResponse()->redirect('/');
                    }
                }
        }
        
    }
    
    public function logIn(array $user)
    {
       
        foreach ($user as $key => $value)
        {
            
            $_SESSION['user']['id'] = $value->getId();
            $_SESSION['user']['pseudo'] = $value->getPseudo();
            $_SESSION['user']['email'] = $value->getEmail();
            $_SESSION['user']['password'] = $value->getPassword();
            $_SESSION['user']['nom'] = $value->getNom();
            $_SESSION['user']['prenom'] = $value->getPrenom();
            $_SESSION['user']['ville'] = $value->getVille();
            $_SESSION['user']['adresse'] = $value->getAdresse();
            $_SESSION['user']['cp'] = $value->getCp();
            $_SESSION['user']['pays'] = $value->getPays();
            $_SESSION['user']['fixe'] = $value->getFixe();
            $_SESSION['user']['portable'] = $value->getPortable();
            $_SESSION['user']['credits'] = $value->getCredits();
            $_SESSION['user']['news'] = $value->getNews();
            $_SESSION['user']['conditions'] = $value->getConditions();
            $_SESSION['user']['civilite'] = $value->getCivilite();
            $_SESSION['user']['ip'] = $value->getIp();
            $_SESSION['user']['role'] = $value->getRole();
            
        }
        $_SESSION['auth'] = true;
        if($_SESSION['user']['role'] ==  md5(_COOKIE_KEY_.'masterboot')){
            $_SESSION['admin'] = true;
        }
    }
    
    public function executeListuser(HttpRequest $request){
     
        $this->page->addVar('title', 'Gestion des utilisateurs');
        
        $manager = $this->managers->getManagerOf('Users');
        
        $data = $manager->getUsers();
        foreach($data as $value){
            if($value->getPays() !=0){
                $country = $this->managers->getManagerOf('Pays')->findPaysById($value->getPays());
                $value->setCountryName(utf8_encode($country->getPays()));
            }else{
                $value->setCountryName('Aucun');
            }
        }
        
        $this->page->addVar('datalist', $data);
        
        $this->leftcolumn();
        $this->rightcolumn();
    }
    
    private function leftcolumn(){
        $out = array();
        $out['add-user.html']= 'Ajouter un Utisateur';
        $out['user.html']= 'Liste';
        
        return $this->page->addVar('left_content', $out);
        
    }
    private function rightcolumn(){
        $out ='Gérez vos utilisateurs, consultez leurs informations. Vous pouvez éditer ou supprimer un profil.';
        return $this->page->addVar('right_content', $out);
    }
    
    public function executeCreate(HttpRequest $request)
    {
        $this->page->addVar('title', 'créer un compte');
        $this->leftcolumn();
        $this->rightcolumn();
        $registerForm = new Form('register','post');
        
        $registerForm->action('add-user.html');
                
        $registerForm->add('Text', 'pseudo')
                     ->label('Pseudo')
                     ->required(true);
        
        $registerForm->add('Password', 'password')
                     ->label('Mot de passe')
                     ->required(true);
        
        $registerForm->add('Password', 'verif_mdp')
                     ->label('Mot de passe(confirmation)')
                     ->required(true);
        
        $registerForm->add('Email', 'email')
                     ->label('E-mail')
                     ->required(true);
        $registerForm->add('Text', 'credits')
                     ->label('Credits')
                     ->required(false);
        
        $registerForm->add('Select', 'role')
                        ->label('Droit d\'accès')
                        ->choices(array(
                            'user' => 'Utilisateur',
                            'masterboot' => 'Administrateur',
                        ))
                ->required(true);
        $registerForm->add('Checkbox', 'newsletter')
                     ->label('J\'accepte de recevoir des mails de la part de Kristoclic')
                     ->required(FALSE);
        
        $registerForm->add('Submit', 'submit')->value("S'inscrire");
         //* ajout de la variable à la page
        if($request->getMethod('post')){
           //test de la validation du post
            if ($registerForm->is_valid($_POST) && $_POST['password']==$_POST['verif_mdp']) {
                
                list($pseudo, $password,$verif_mdp,$email,$news,$role) = $registerForm->get_cleaned_data('pseudo','password','verif_mdp','email','newsletter','role');
                $news = isset($news)?1:0;
                $manager = $this->managers->getManagerOf('Users');
        
                $user = $manager->verifInscription($pseudo, $email);
                
                $ipProt1 = $request->resquestIp().':'.$request->resquestPort();
                
                $ipProt = $manager->verifIpPort($ipProt1);
                if(!empty ($user)){
                    $this->errors ='Ce pseudo ou E-mail est déjà utilisé';
                    $registerForm->bound($_POST);
                }else{
                    if(!empty ($ipProt)){
                        $this->errors ="Un compte a été déjà créé aujourd'hui depuis votre machine";
                        $registerForm->bound($_POST);
                    }else{
                       if($manager->addUser($pseudo,$email,$password,$ipProt1,$news,$role)){
                           $param = array();
                           $param['adress']=$email;
                           $param['from']=__EMAIL__;
                           $param['destinataire']=$email;
                           $param['subjet'] = 'Votre inscription sur ' . __SITE__;
                           $param['message'] = ' Récapitulatif de vos informations :<br /><br />
		 
                             ' . $pseudo . '<br />
                             ' . $email . '<br />
                             ' . $password . '<br /><br />Vous pouvez modifier votre mot de passe une fois connecté';
                           $this->sendMail($param);
                           $this->app->httpResponse()->redirect('user.html');
                       }else{
                           $this->errors ="Echec lors de l'inscriptions";
                           $registerForm->bound($_POST);
                       }
                        
                    }
                }
            }else{
                $this->errors ="Vérifier les données saisies";
                $registerForm->bound($_POST);
            }
        }else{
            $registerForm->bound($_POST);
        }
        $this->page->addVar('errors', $this->errors);
        $this->page->addVar('dataForm', $registerForm);
    }
    
    public function executeDelete(HttpRequest $request){
        
        $manager = $this->managers->getManagerOf('Users');
        if($request->getExists('id')){
            $out['id'] = $request->getData('id');
            if($manager->deleteUser($out)){
                $this->errors = 'suppression réussie';
            }else{
                $this->errors = 'Echec lors de la suppression';
            }
            $this->app()->httpResponse()->redirect('user.html');
            
        }
    }
    
    public function executeEdit(HttpRequest $request){
        $this->page->addVar('title', 'Editer un compte');
        $this->leftcolumn();
        $this->rightcolumn();
        $manager = $this->managers->getManagerOf('Users');
        $dataForm = new Form('edit','post');
        
        $dataForm->add('Text', 'pseudo')
                     ->label('Pseudo')
                     ->required(true);
        
        $dataForm->add('Password', 'password')
                     ->label('Mot de passe')
                     ->required(false);
        
        $dataForm->add('Password', 'verif_mdp')
                     ->label('Mot de passe(confirmation)')
                     ->required(false);
        $dataForm->add('Email', 'email')
                     ->label('E-mail')
                     ->required(true);
        $dataForm->add('Text', 'credits')
                     ->label('Credits')
                     ->required(false);
        $dataForm->add('Select', 'role')
                    ->label('Droit d\'accès')
                    ->choices(array(
                        md5(_COOKIE_KEY_.'user') => 'Utilisateur',
                        md5(_COOKIE_KEY_.'masterboot') => 'Administrateur',
                    ))
                    ->required(true);
        if($request->getExists('id')){
            
            $dataForm->add('Hidden', 'id')->value($request->getData('id'));
            $this->page->addVar('title', 'Modifier un contenu');
            $dataForm->add('Submit', 'submit')->value('Modifier');
            
            $data = $manager->findUserById(intval($request->getData('id')));
            $data_array['pseudo'] = $data->getPseudo();
            $data_array['email'] = $data->getEmail();
            $data_array['credits'] = $data->getCredits();
            $data_array['role'] = $data->getRole();
            $dataForm->add('Hidden', 'passwordH')->value($data->getPassword());
            //* ajout de la variable à la page
            if($request->getMethod('post')){
            //test de la validation du post
                if ($dataForm->is_valid($_POST) && $_POST['password']==$_POST['verif_mdp']) {
                    //mise à jour de l'enregistrement
                    $dataUpdate = array();
                    
                    list($pseudo, $password,$credits,$email,$passwordH,$role) = $dataForm->get_cleaned_data('pseudo','password','credits','email','passwordH','role');
                    //on si le pseudo et l'email existe et appartiennent à cet utilisateur
                    $user = $manager->verifInscription($pseudo, $email);
                    if(!empty ($user) && $request->getData('id') !=$user[0]->getId()){
                        $this->errors ='Ce pseudo ou E-mail est déjà utilisé';
                        $dataForm->bound($_POST);
                    }else{
                        $dataUpdate['email'] = $email;
                        $dataUpdate['pseudo'] = $pseudo;
                        $dataUpdate['password'] = !empty($password)?md5($password):$passwordH;
                        $dataUpdate['credits'] = $credits;
                        $dataUpdate['role'] = md5(_COOKIE_KEY_.$role);
                        
                        $manager->updateRecord($manager->getTableName(),$dataUpdate,intval($request->getData('id')) );
                        $this->app()->httpResponse()->redirect('user.html');
                    }
                }else{
                    $this->errors ="Vérifier les données saisies";
                    $dataForm->bound($_POST);
                    //$manager->updateRecord($manager->getTableName(),$dataUpdate,intval($request->getData('id')) );
                }
            }else{
                $dataForm->bound($data_array);
            }
            
            
        }else $this->app()->httpResponse()->redirect('user.html');
        
        $this->page->addVar('errors', $this->errors);
        $this->page->addVar('dataForm', $dataForm);
    }
    
    public function executeDetailUser(HttpRequest $request){
        $this->page->addVar('title', 'Différentes information d\'un utilisateur');
        $this->leftcolumn();
        $this->rightcolumn();
        $manager = $this->managers->getManagerOf('Users');
        $data = $manager->findUserById(intval($request->getData('id')));
        if($data->getPays() !=0){
                $country = $this->managers->getManagerOf('Pays')->findPaysById($data->getPays());
                $data->setCountryName(utf8_encode($country->getPays()));
            }else{
                $data->setCountryName('Aucun');
            }
        $this->page->addVar('data',$data);
    }
}

?>
